<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input v-model.trim="name" type="text" />
    </div>
    <div>
      <span>年龄:</span>
      <input v-model.number="age" type="number" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addFn">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in arr" :key="item.id">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="delFn(index)">删除</button>
            <button @click="editFn(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      arr: [
        {
          name: "tom",
          age: 19,
          gender: "男",
          id: 1,
        },
        {
          name: "jone",
          age: 21,
          gender: "女",
          id: 2,
        },
      ],
      name: "",
      age: 0,
      gender: "男",
      isEdit: false, // isEdit为false的时候表示新增数据，true表示编辑
      curIndex: "", // 点击编辑按钮时保存的当前行下标值
    };
  },
  methods: {
    // 新增 / 编辑
    addFn() {
      if (this.name == "") {
        alert("学生姓名不能为空！");
        return;
      }
      if (this.age <= 0) {
        alert("年龄不能小于等于0");
        return;
      }
      if (this.isEdit) {
        console.log("编辑");
        this.arr[this.curIndex].name = this.name;
        this.arr[this.curIndex].age = this.age;
        this.arr[this.curIndex].gender = this.gender;
        this.isEdit = false;
        // 编辑
      } else {
        // 新增
        let id = this.arr.length ? this.arr[this.arr.length - 1].id + 1 : 1;
        this.arr.push({
          name: this.name,
          age: this.age,
          gender: this.gender,
          id: id,
        });
      }
    },
    // 点击编辑按钮，
    /**
     * 1、给编辑按钮绑定点击事件，并传点击那一行的学生id或者下标值
     * 2、在事件处理函数中点击那一行的学生信息
     * 3、将获取到的信息赋值给name、age、gender属性
     *
     * */
    editFn(index) {
      this.curIndex = index;
      let obj = this.arr[index];
      // console.log(obj);
      this.name = obj.name;
      this.age = obj.age;
      this.gender = obj.gender;
      this.isEdit = true;
    },
    // 删除
    delFn(index) {
      this.arr.splice(index, 1);
    },
  },
};
</script>
